package com.base.social.auth;

import com.base.core.enums.SystemCodeEnum;
import com.base.core.lang.StringUtils;
import com.base.core.network.SimpleHttpUtils;
import com.base.core.network.http.ResponseEntity;
import com.base.core.utils.R;
import com.base.core.utils.UrlBuilderUtils;
import com.base.core.utils.UUIdUtils;
import com.base.social.cache.AuthDefaultStateCache;
import com.base.social.cache.AuthStateCache;
import com.base.social.config.AuthConfig;
import com.base.social.config.AuthSource;
import com.base.social.domain.AuthCallbackParams;
import com.base.social.domain.AuthToken;
import com.base.social.domain.AuthUser;
import com.base.social.exception.AuthRuntimeException;
import com.base.social.utils.AuthCheckerUtils;

import javax.xml.ws.Response;

/**
 * 默认的request处理类
 *
 * @since 1.0.0
 */
public abstract class AuthDefault implements Auth {
    protected AuthConfig config;
    protected AuthSource source;
    protected AuthStateCache authStateCache;

    public AuthDefault(AuthConfig config, AuthSource source) {
        this(config, source, AuthDefaultStateCache.INSTANCE);
    }

    public AuthDefault(AuthConfig config, AuthSource source, AuthStateCache authStateCache) {
        this.config = config;
        this.source = source;
        this.authStateCache = authStateCache;
        if (!AuthCheckerUtils.isSupportedAuth(config, source)) {
            throw new AuthRuntimeException(SystemCodeEnum.PARAMETER_INCOMPLETE, source);
        }
        // 校验配置合法性
        //AuthCheckerUtils.checkConfig(config, source);
    }

    /**
     * 获取access token
     *
     * @param authCallback 授权成功后的回调参数
     * @return token
     * @see AuthDefault#authorize(String)
     */
    protected abstract AuthToken createAccessToken(AuthCallbackParams authCallback);

    /**
     * 统一的登录入口。当通过{@link AuthDefault#authorize(String)}授权成功后，会跳转到调用方的相关回调方法中
     * 方法的入参可以使用{@code AuthCallback}，{@code AuthCallback}类中封装好了OAuth2授权回调所需要的参数
     *
     * @param authCallback 用于接收回调参数的实体
     * @return R
     */
    @Override
    public R login(AuthCallbackParams authCallback) {
        try {
            AuthCheckerUtils.checkCode(source, authCallback);
            AuthCheckerUtils.checkState(authCallback.getState(), source, authStateCache);

            AuthToken authToken = this.createAccessToken(authCallback);
            AuthUser user = this.findUserInfo(authToken);
            return R.success(user);
        } catch (Exception e) {
            //Log.error("Failed to login with oauth authorization.", e);
            return this.responseError(e);
        }
    }

    @Override
    public R oauthGetToken(AuthCallbackParams authCallback) {
        try {
            AuthCheckerUtils.checkCode(source, authCallback);
//            AuthCheckerUtils.checkState(authCallback.getState(), source, authStateCache);
            AuthToken authToken = this.createAccessToken(authCallback);
            return R.success(authToken);
        } catch (Exception e) {
            //Log.error("Failed to login with oauth authorization.", e);
            return this.responseError(e);
        }
    }

    /**
     * 处理{@link AuthDefault#login(AuthCallbackParams)} 发生异常的情况，统一响应参数
     *
     * @param e 具体的异常
     * @return R
     */
    private R responseError(Exception e) {
        int errorCode = SystemCodeEnum.FAILURE.getCode();
        String errorMsg = e.getMessage();
        if (e instanceof AuthRuntimeException) {
            AuthRuntimeException authRuntimeException = ((AuthRuntimeException) e);
            errorCode = authRuntimeException.getErrorCode();
            if (StringUtils.isNotEmpty(authRuntimeException.getErrorMsg())) {
                errorMsg = authRuntimeException.getErrorMsg();
            }
        }
        return R.fail(errorCode,errorMsg);
    }

    /**
     * 返回带{@code state}参数的授权url，授权回调时会带上这个{@code state}
     * 此为默认方法仅支持网页应用
     * @param state state 验证授权流程的参数，可以防止csrf
     * @return 返回授权地址
     * @since 1.9.3
     */
    @Override
    public String authorize(String state) {
        return UrlBuilderUtils.fromBaseUrl(source.authorize())
                .queryParam("response_type", config.getResponseType())
                .queryParam("client_id", config.getClientId())
                .queryParam("redirect_uri", config.getRedirectUri())
                .queryParam("state", getRealState(state))
                .queryParam("scope", config.getScope())
                .build();
    }

    /**
     * 返回获取accessToken的url
     *
     * @param code 授权码
     * @return 返回获取accessToken的url
     */
    protected String accessTokenUrl(String code) {
        return UrlBuilderUtils.fromBaseUrl(source.accessToken())
                .queryParam("code", code)
                .queryParam("client_id", config.getClientId())
                .queryParam("client_secret", config.getClientSecret())
                .queryParam("grant_type", "authorization_code")
                .queryParam("redirect_uri", config.getRedirectUri())
                .build();
    }

    /**
     * 返回获取accessToken的url
     *
     * @param refreshToken refreshToken
     * @return 返回获取accessToken的url
     */
    protected String refreshTokenUrl(String refreshToken) {
        return UrlBuilderUtils.fromBaseUrl(source.refresh())
                .queryParam("client_id", config.getClientId())
                .queryParam("client_secret", config.getClientSecret())
                .queryParam("refresh_token", refreshToken)
                .queryParam("grant_type", "refresh_token")
                .queryParam("redirect_uri", config.getRedirectUri())
                .build();
    }

    /**
     * 返回获取userInfo的url
     *
     * @param authToken token
     * @return 返回获取userInfo的url
     */
    protected String userInfoUrl(AuthToken authToken) {
        return UrlBuilderUtils.fromBaseUrl(source.userInfo()).queryParam("access_token", authToken.getAccessToken()).build();
    }

    /**
     * 返回获取revoke authorization的url
     *
     * @param authToken token
     * @return 返回获取revoke authorization的url
     */
    protected String revokeUrl(AuthToken authToken) {
        return UrlBuilderUtils.fromBaseUrl(source.revoke()).queryParam("access_token", authToken.getAccessToken()).build();
    }

    /**
     * 获取state，如果为空， 则默认取当前日期的时间戳
     *
     * @param state 原始的state
     * @return 返回不为null的state
     */
    protected String getRealState(String state) {
        if (StringUtils.isEmpty(state)) {
            state = UUIdUtils.genUuid();
        }
        // 缓存state
        authStateCache.cache(state, state);
        return state;
    }

    /**
     * 通用的 authorizationCode 协议
     *
     * @param code code码
     * @return R
     */
    protected String doPostAuthorizationCode(String code) {
        ResponseEntity responseEntity = SimpleHttpUtils.post(accessTokenUrl(code));
        return responseEntity.getBody();
    }

    /**
     * 通用的 authorizationCode 协议
     *
     * @param code code码
     * @return R
     */
    protected String doGetAuthorizationCode(String code) {
        ResponseEntity responseEntity = SimpleHttpUtils.get(accessTokenUrl(code));
        return responseEntity.getBody();
    }

    /**
     * 通用的 用户信息
     *
     * @param authToken token封装
     * @return R
     */
    @Deprecated
    protected String doPostUserInfo(AuthToken authToken) {
        ResponseEntity responseEntity = SimpleHttpUtils.post(userInfoUrl(authToken));
        return responseEntity.getBody();
    }

    /**
     * 通用的 用户信息
     *
     * @param authToken token封装
     * @return R
     */
    protected String doGetUserInfo(AuthToken authToken) {
        ResponseEntity responseEntity = SimpleHttpUtils.get(userInfoUrl(authToken));
        return responseEntity.getBody();
    }

    /**
     * 通用的post形式的取消授权方法
     *
     * @param authToken token封装
     * @return R
     */
    @Deprecated
    protected String doPostRevoke(AuthToken authToken) {
        ResponseEntity responseEntity = SimpleHttpUtils.post(revokeUrl(authToken));
        return responseEntity.getBody();
    }

    /**
     * 通用的get形式的取消授权方法
     *
     * @param authToken token封装
     * @return R
     */
    protected String doGetRevoke(AuthToken authToken) {
        ResponseEntity responseEntity = SimpleHttpUtils.get(revokeUrl(authToken));
        return responseEntity.getBody();
    }

}
